import Vue from 'vue'
import VueRouter from 'vue-router'
//导入进度条插件
import NProgress from 'nprogress'
//导入进度条样式
import 'nprogress/nprogress.css'
import userApi from '../request/userApi'
const Home = () => import('../view/Home')
const Login = () => import('../view/Login')
const Register = () => import('../view/Register')
const Personal = () => import('../view/Personal')
const Explore = () => import('../view/Explore')
const Photographer=() => import('../view/Photographer')
const User = () => import('../view/User')
const Upload = () => import('../view/Upload')
const Search = () => import('../view/Search')
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { title: 'NiLiNiLi' },
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录' },
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { title: '注册' },
  },
  {
    path: '/personal',
    name: 'Personal',
    component: Personal,
    meta: { title: '个人中心' }
  },
  {
    path: '/explore',
    name: 'Explore',
    component: Explore,
    meta: { title: '探索' }
  },
  {
    path: '/photographer',
    name: 'Photographer',
    component: Photographer,
    meta: { title: '摄影师' }
  },
  {
    path: '/user/:id',
    name: 'User',
    component: User,
    meta: { title: '用户详情' }
  },
  {
    path: '/upload',
    name: 'Upload',
    component: Upload,
    meta: { title: '上传' }
  },
  {
    path: '/search/:name',
    name: 'Search',
    component: Search,
    meta: { title: '搜索' }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.path === '/main') {
    NProgress.done();
    return next();
  }
  if(to.path === '/personal' || to.path === '/upload'){
    userApi.getUserInfo().then(res => {
      if(res.code === 200){
        NProgress.done();
        next()
      }else{
        NProgress.done();
        next('/login')
        // next('')
      }
    })
  }
  next();
})

router.afterEach(() => {
  NProgress.done();
  // 在即将进入新的页面组件前，关闭掉进度条
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
